package com.moleq.base;

import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.Map;

import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;

import com.moleq.service.ServiceManager;
import com.moleq.util.ImageUtil;

public class AsyncImageLoader {
	private Map<String, SoftReference<Drawable>> imageCache = new HashMap<String, SoftReference<Drawable>>();

//	private ItemPicService mPicService;
	
	public Drawable loadDrawable(final String imageUrl,final ImageCallback callback) {
		
		if (imageCache.containsKey(imageUrl)) {
			SoftReference<Drawable> softReference = imageCache.get(imageUrl);
			if (softReference.get() != null) {
				return softReference.get();
			}
		}
		
		final Handler handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				callback.imageLoaded((Drawable) msg.obj, imageUrl);
			}
		};
		
		new Thread() {
			public void run() {
				Drawable drawable = loadImageFromUrl(imageUrl);
				imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
				handler.sendMessage(handler.obtainMessage(0, drawable));
			};
		}.start();
		return null;
	}

	
	
	protected Drawable loadImageFromUrl(String imageUrl) {
		try {
			
//			return ImageUtil.bitmapToDrawable(mPicService.getSmallImageByUPC(imageUrl));
			
//			return loadImageFromUrl(imageUrl,120,90);
			
//			Drawable db = null;
//			long startTime=System.currentTimeMillis();   //获取开始时间  
//			db = mPicService.getImageByID(imageUrl);
//			long endTime=System.currentTimeMillis(); //获取结束时间  
//			Log.i("Time",imageUrl +"-> used time : "+(endTime-startTime)+"ms");   
//			
//			return db;
			
			return ServiceManager.getInstance().mPicService.getImageByID(imageUrl);
					
			//return Drawable.createFromPath(imageUrl);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	protected Drawable loadImageFromUrl(String imageUrl,int width, int height) {
		try {
			
			return ImageUtil.bitmapToDrawable(ServiceManager.getInstance().mPicService.getImage(imageUrl, width, height));
					
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	
	protected Drawable loadImageFromPath(String phothName) {
		try {
			
			return null;
			
			//return mPicService.getImageByID(imageUrl);
					
			//return Drawable.createFromPath(imageUrl);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public interface ImageCallback {
		public void imageLoaded(Drawable imageDrawable, String imageUrl);
	}


}
